import {
  defineStore
} from 'pinia'
export const cartStore = defineStore('cart', {
  state: () => {
    return {
    cartlist:{
      list:[]
    }
    }
  },
   getters: {
     //总价
      total() {
        const list = this.cartlist.list
        return list.length
          ? list.reduce((acc, item) => (item.checked ? acc + item.unit_price * item.quantity : acc), 0)
          : 0
      },
    //总数
     allcount() {
       const list = this.cartlist.list
       return list.length
         ? list.reduce((acc, item) => ( acc + item.quantity) , 0)
         : 0
     },
    //全选
      allChecked() {
        const list = this.cartlist.list
        return list.length ? list.every(item => item.checked) : false
      },
      //选中
      onleChecked() {
        const list = this.cartlist.list
        return list.length ? list.some(item => item.checked) : false
      }
    },
  actions: {
   //发送加入购物车请求
   async addcart(data){
     const response = await uni.$http.post("/cart/addcart",data)
     uni.showToast({
       title: response.data,
       duration: 2000,
       icon: "success"
     });
   },

  //发送获取购物车信息请求
  async getcart(){
    const response = await uni.$http.get("/cart/getcart")
     this.cartlist.list = response.data
  },
  //数量加一
  async addcount(id){
     const response = await uni.$http.put("/cart/addcount",{"id":id})
     if(response.statusCode===200){
       this.getcart()
     }
  },
  //数量减一
  async cutcount(id){
     const response = await uni.$http.put("/cart/cutcount",{"id":id})
    if(response.statusCode===200){
      this.getcart()
    }
  },
  //更改值
  async setcount(data){
     const response = await uni.$http.put("/cart/setcount",data)
    if(response.statusCode===200){
      this.getcart()
    }
  },
  //删除购物车条目
  async deletecart(id){
     const response = await uni.$http.delete("/cart/deletecart",{"id":id})
    if(response.statusCode===200){
      this.getcart()
      uni.showToast({
        title: "删除成功",
        duration: 2000,
        icon: "success"
      });
    }
  },
  //选中
  async chected(id){
     const response = await uni.$http.put("/cart/chected",{"id":id})
   if(response.statusCode===200){
     this.getcart()
   }
  },
  //全选
  async allchected(bool){
    const response = await uni.$http.put("/cart/allchected",{"bool":bool})
   if(response.statusCode===200){
     this.getcart()
    uni.showToast({
      title: "删除成功",
      duration: 2000,
      icon: "success"
    });
   }
  },
  //删除选中
  async detechect(){
    const response = await uni.$http.delete("/cart/detechected")
    if(response.statusCode===200){
     this.getcart()
   }
  },
   }
})